# -*- coding: utf-8 -*-
"""
    scheduler
    ~~~~~~~~~

    Task scheduler.

    :copyright: 2010 by Baptiste Lepilleur.
    :license: Apache License 2.0, see LICENSE.txt for more details.
"""
from tipfy import RequestHandler, Response, request, Unauthorized, NotFound
from tipfy.ext.db import get_entity_from_protobuf, get_protobuf_from_entity, get_by_key_name_or_404
import logging
from google.appengine.ext import db
from google.appengine.api import memcache
from sourcechangenotification import SourceChange

MAX_SLUG_NAME_LENGTH = 16

class AgentTaskId(db.Model):
    """Next Id generator for AgentTask.
    """
    next_id = db.IntegerProperty(required=True)

class AgentTask(db.Model):
    """A task associated to an agent.
    """
    agent_id = db.IntegerProperty(required=True)
    task_id = db.IntegerProperty(required=True)
    kind = db.StringProperty(required=True)
    task_key = db.StringProperty(required=True)

def _next_agent_task_id( agent_id ):
    """
    Returns a new unique task id for a given agent. Task id are in
    increasing order.
    """
    def tnx():
        next_task = AgentTaskId.get_by_id( agent_id )
        if not next_task:
            next_task = AgentTaskId( key=db.Key.from_path(agent_id),
                next_id=0 )
        next_task.next_id = next_task.next_id + 1
        next_task.put()
    db.run_in_transaction(tnx)


class OnSourceChangeHandler(RequestHandler):
    """
    Assign the SourceChangeTask to all agent associated to the project.
    """
    def post( self, source_change_key_name=None):
        source_change = get_by_key_name_or_404( SourceChange,
            source_change_key_name )
        # Find agents associated to that project
        agent_ids = agentmanager.get_agent_id_list_for_project(
            source_change.project_id )
        # Associates the change to each agent
        # ? But agent needs to fetch task in order


class AssignSourceChangeTaskHandler(RequestHandler):
    """
    Assign a SourceChange task to a given agent.
    """
    def post( self, agent_id=None, source_change_key_name=None):
        agent_id = int(agent_id)
        source_change = get_by_key_name_or_404( SourceChange,
            source_change_key_name )
        task_id = _next_agent_task_id( agent_id )

        task = AgentTask( key_name='%d:%d' % (task_id,agent_id),
            task_id=task_id,
            agent_id=agent_id,
            task_key=source_change_key_name )
        task.put()
